package com.simen.hellobytes;

import com.simen.hellobytes.code.FilterCommentLine;
import com.simen.hellobytes.interfaces.LineIterator;

import java.io.*;

public class CodeUtil {

    public static String compressJsScript(File file) throws IOException {
        return compressJsScript(new FileInputStream(file));
    }

    public static String compressJsScript(InputStream is) throws IOException {
        final StringBuilder builder=new StringBuilder();
        final FilterCommentLine filterCommentLine =new FilterCommentLine();
        IOUtil.iteratorStreamLine(is, new LineIterator() {
            @Override
            public void onRead(String line) throws IOException {
                if(line.length()==0) return;
                String noCommentLine=filterCommentLine.swallowLine(line.trim());
                if(noCommentLine==null) return;

                String newLine=noCommentLine.replaceAll("[\\s]{2,}"," ");
                builder.append(newLine);
                if(newLine.length()!=0 && !newLine.endsWith(";")){
                    builder.append(" ");
                }
            }
        });
        filterCommentLine.swallowEnd();
        return builder.toString();
    }

    public static String compressJsScript(String jsScript) throws IOException {
        BufferedReader bufferedReader=new BufferedReader(new StringReader(jsScript));
        StringBuilder builder=new StringBuilder();
        String line=null;
        while ((line=bufferedReader.readLine())!=null){
            String newLine=line.trim().replaceAll("[\\s]{2,}"," ");
            builder.append(newLine);
            if(!newLine.endsWith(";")){
                builder.append(" ");
            }
        }

        return line;
    }

}
